package com.mdlib.helper.ui.fragments.sect.money;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.hn.plt.config.ClientConfig;
import com.ljlib.core.BaseApplication;
import com.ljlib.core.util.EmptyUtils;
import com.ljlib.help.R;
import com.mdlib.helper.api.DataManager;
import com.mdlib.helper.api.network.RxHelper;
import com.mdlib.helper.api.network.RxSubscribe;
import com.mdlib.helper.base.BaseTitleFragment;
import com.mdlib.helper.event.PayEvent;
import com.mdlib.helper.model.BaseResult;
import com.mdlib.helper.model.entity.OrderIdInfo;
import com.mdlib.helper.model.entity.OrderMoney;
import com.mdlib.helper.model.entity.RechargeEntity;
import com.mdlib.helper.ui.UIHelper;
import com.mdlib.helper.utils.PayResult;
import com.mdlib.helper.utils.ToastUtil;
import com.orhanobut.logger.Logger;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.Bind;
import butterknife.OnClick;

import static com.mdlib.helper.ui.UIHelper.ALIPAY;
import static com.mdlib.helper.ui.UIHelper.BALANCE;
import static com.mdlib.helper.ui.UIHelper.WECHAT;

/**
 * 作者：HQY on 16/11/22 10:32
 * 邮箱：hqy_xz@126.com
 */

public class OrdersFragment extends BaseTitleFragment {


    @Bind(R.id.rb_order_balance)
    RadioButton mRbOrderBalance;
    @Bind(R.id.rb_order_wechat)
    RadioButton mRbOrderWechat;
    @Bind(R.id.rb_order_alipay)
    RadioButton mRbOrderAlipay;
    @Bind(R.id.tv_order_pay)
    TextView mTvOrderPay;
    @Bind(R.id.tv_order_service_money)
    TextView mTvOrderServiceMoney;
    @Bind(R.id.tv_order_total_money)
    TextView mTvOrderTotalMoney;
    private Dialog mOutOrder;
    private OrderIdInfo orderIdInfo;
    private String payType = BALANCE;
    private IWXAPI api;
    private static final int SDK_PAY_FLAG = 1;

    public static OrdersFragment newInstance(OrderIdInfo idInfo) {
        OrdersFragment fragment = new OrdersFragment();
        Bundle bundle = new Bundle();
        bundle.putSerializable(UIHelper.ORDERIDINFO, idInfo);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (EmptyUtils.isEmpty(getArguments())) {
            removeFragment();
        }
        orderIdInfo = (OrderIdInfo) getArguments().getSerializable(UIHelper.ORDERIDINFO);
        EventBus.getDefault().register(this);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    protected void initBundle(Bundle bundle) {
        super.initBundle(bundle);
        api = WXAPIFactory.createWXAPI(getActivity().getApplicationContext(), ClientConfig.WX_APP_ID);
        api.registerApp(ClientConfig.WX_APP_ID);
    }

    @Override
    protected int getContentLayoutId() {
        return R.layout.fragment_orders;
    }

    @Override
    protected void initView(View rootView) {
        super.initView(rootView);
        setTitle(R.string.order_pay_title, R.color.white)
                .setTitleBgColor(R.color.generic_view_bg)
                .setImgLeftListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mOutOrder = new Dialog(getActivity(), R.style.dialog);
                        mOutOrder.setContentView(R.layout.dialog_out_order);
                        TextView contiune = (TextView) mOutOrder.findViewById(R.id.tv_dialog_continue);
                        TextView out = (TextView) mOutOrder.findViewById(R.id.tv_dialog_out);
                        contiune.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                mOutOrder.dismiss();
                            }
                        });
                        out.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                closeOrder();
                                mOutOrder.dismiss();
                            }
                        });
                        mOutOrder.show();
                    }
                });
        getOderInfo();
    }

    private void closeOrder() {
        addSubscribe(DataManager.getInstance().getUserApi()
                .closeOrder(orderIdInfo.getBusId())
                .compose(RxHelper.<BaseResult>rxSchedulerHelper())
                .subscribe(new RxSubscribe<BaseResult>() {
                    @Override
                    protected void onSucc(BaseResult baseResult) {
                        ToastUtil.showToast(baseResult.msg);
                        getActivity().finish();
                    }

                    @Override
                    protected void onFail(String msg) {
                        ToastUtil.showToast(msg);
                    }
                }));
    }

    private void getOderInfo() {
        addSubscribe(DataManager.getInstance().getUserApi()
                .getOrderMoney(orderIdInfo.getBusId())
                .compose(RxHelper.<OrderMoney>defaultHandleResult())
                .subscribe(new RxSubscribe<OrderMoney>() {
                    @Override
                    protected void onSucc(OrderMoney orderMoney) {
                        mTvOrderServiceMoney.setText("￥" + orderMoney.getService_money());
                        mTvOrderTotalMoney.setText("￥" + orderMoney.getTotal_money());
                    }

                    @Override
                    protected void onFail(String msg) {
                        ToastUtil.showToast(msg);
                    }
                }));

    }

    @OnClick({R.id.rb_order_balance, R.id.rb_order_wechat, R.id.rb_order_alipay, R.id.tv_order_pay})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.rb_order_balance:
                payType = BALANCE;
                mRbOrderBalance.setChecked(true);
                mRbOrderWechat.setChecked(false);
                mRbOrderAlipay.setChecked(false);
                break;
            case R.id.rb_order_wechat:
                payType = WECHAT;
                mRbOrderBalance.setChecked(false);
                mRbOrderWechat.setChecked(true);
                mRbOrderAlipay.setChecked(false);
                break;
            case R.id.rb_order_alipay:
                payType = ALIPAY;
                mRbOrderBalance.setChecked(false);
                mRbOrderWechat.setChecked(false);
                mRbOrderAlipay.setChecked(true);
                break;
            case R.id.tv_order_pay:
                payOrder();
                break;
        }
    }


    private void payOrder() {
        addSubscribe(DataManager.getInstance().getUserApi()
                .payOrder(orderIdInfo.getOrderId(), payType)
                .compose(RxHelper.<RechargeEntity>defaultHandleResult())
                .subscribe(new RxSubscribe<RechargeEntity>() {
                    @Override
                    protected void onSucc(RechargeEntity rechargeEntity) {
                        pay(rechargeEntity);
                    }

                    @Override
                    protected void onFail(String msg) {
                        ToastUtil.showToast(msg);
                    }
                }));
    }
    class MyThread extends Thread {
        String Order_Id = "";
        int Order_Price;

        public MyThread(String orderId, String price) {
            Order_Id = orderId;
            Order_Price = (int) (Double.parseDouble(price) * 100);
        }

        public void run() {
            //wxUtil.load(getActivity().getApplicationContext(), "nicai", "支付", Order_Id, Order_Price);
        }
    }
    private void pay(final RechargeEntity payEntity) {
        if (payType.equals(BALANCE)) {
            ToastUtil.showToast("支付成功");
            getActivity().finish();
        } else if (payType.equals(WECHAT)) {
            api.registerApp(ClientConfig.WX_APP_ID);// 将该app注册到微信
            PayReq req = new PayReq();
            req.appId = payEntity.getAppid();
            req.partnerId = payEntity.getPartnerid();
            req.prepayId = payEntity.getPrepayid();
            req.nonceStr = payEntity.getNoncestr();
            req.timeStamp = String.valueOf(payEntity.getTimestamp());
            req.packageValue = payEntity.getPackageX();
            req.sign = payEntity.getSign();
            // 在支付之前，如果应用没有注册到微信，应该先调用IWXMsg.registerApp将应用注册到微信
            api.sendReq(req);
        } else if (payType.equals(ALIPAY)) {
            final String orderinfo = payEntity.getSign();
            Runnable payRunnable = new Runnable() {

                @Override
                public void run() {
                    // 构造PayTask 对象
                    PayTask alipay = new PayTask(getActivity());
                    // 调用支付接口，获取支付结果
                    String result = alipay.pay(orderinfo, true);
                    Message msg = new Message();
                    msg.what = SDK_PAY_FLAG;
                    msg.obj = result;
                    mHandler.sendMessage(msg);
                }
            };
            // 必须异步调用
            Thread payThread = new Thread(payRunnable);
            payThread.start();
        }
    }

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    PayResult payResult = new PayResult((String) msg.obj);
                    /**
                     * 同步返回的结果必须放置到服务端进行验证（验证的规则请看https://doc.open.alipay.com/doc2/detail.htm?spm=0.0.0.0.xdvAU6&treeId=59&articleId=103665&docType=1) 建议商户依赖异步通知
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息


                    String resultStatus = payResult.getResultStatus();
                    Logger.e("支付宝返回结果：" + resultInfo + "   " + resultStatus);
                    // 判断resultStatus 为“9000”则代表支付成功，具体状态码代表含义可参考接口文档
                    if (TextUtils.equals(resultStatus, "9000")) {
                       ToastUtil.showToast("支付成功");
                        getActivity().finish();
                    } else {
                        // 判断resultStatus 为非"9000"则代表可能支付失败
                        // "8000"代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）
                        if (TextUtils.equals(resultStatus, "8000")) {
                            Toast.makeText(getActivity(), "支付结果确认中", Toast.LENGTH_SHORT).show();

                        } else {
                            // 其他值就可以判断为支付失败，包括用户主动取消支付，或者系统返回的错误
                            Toast.makeText(getActivity(), "支付失败", Toast.LENGTH_SHORT).show();
                        }
                    }
                    break;
                }
                default:
                    break;
            }
        }

        ;
    };

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(PayEvent event) {
        if (event.getSucc().equals("0")) {
            ToastUtil.showToast("支付成功");
            getActivity().finish();
        }
    }
}
